package com.gzz.common.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.gzz.common.config.Result;
import com.gzz.manage.sys.user.User;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

/**
 * @类说明 【验证令牌】过滤器
 * @author 高振中
 * @date 2021-02-01 20:20:20
 **/
@Slf4j
@Component
public class ValidateTokenFilter extends OncePerRequestFilter {
	@Autowired
	private Cache<Integer, User> userCache;// 用于存放用户登录信息的guava缓存
	@Autowired
	private ObjectMapper mapper;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String path = request.getServletPath();
		String token = request.getHeader("token");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "application/json");
// 		log.error("path={}",path);
		if (PathTools.isSkip(path)) {
			filterChain.doFilter(request, response);
			return;
		}

		if (StringUtils.isEmpty(token) || token.equals("null")) {
			log.error("token为空,请重新登录！");
			response.getWriter().write(writeResult(201, "token为空,请重新登录！"));
			return;
		}
		Claims claims = JwtTools.parseToken(token);
		Boolean expired = JwtTools.isTokenExpired(claims);
		if (expired) {
			log.error("token过期,请重新登录！");
			response.getWriter().write(writeResult(201, "token过期,请重新登录！"));
			return;
		}
		Integer userId = JwtTools.getUserId(token);
		request.setAttribute("userId", userId);
		User user = userCache.getIfPresent(userId);

		if (user == null) {
			log.error("token失效,请重新登录！");
			response.getWriter().write(writeResult(201, "token失效,请重新登录！"));
			return;
		}

		filterChain.doFilter(request, response);
	}

	private String writeResult(int code, String msg) throws JsonProcessingException {
		return new String(mapper.writeValueAsBytes(Result.error(201, msg)));
	}

}